from typing import Any, Optional
from dataclasses import dataclass
import json
from .status import ResponseStatus


@dataclass
class ApiResponse:
    """
    统一API响应模型
    """
    code: int
    message: str
    data: Any = None
    request_id: Optional[str] = None
    
    def to_dict(self) -> dict:
        """转换为字典格式"""
        result = {
            'code': self.code,
            'message': self.message,
            'data': self.data,
        }
        if self.request_id:
            result['requestId'] = self.request_id
        return result
    
    def to_json(self) -> str:
        """转换为JSON字符串"""
        return json.dumps(self.to_dict(), ensure_ascii=False)


# 为了向后兼容，保留原有的类结构
class ResponseCode:
    """
    响应状态码常量（向后兼容）
    """
    # 成功
    SUCCESS = ResponseStatus.SUCCESS.code
    
    # 客户端错误
    BAD_REQUEST = ResponseStatus.BAD_REQUEST.code
    UNAUTHORIZED = ResponseStatus.UNAUTHORIZED.code
    FORBIDDEN = ResponseStatus.FORBIDDEN.code
    NOT_FOUND = ResponseStatus.NOT_FOUND.code
    METHOD_NOT_ALLOWED = ResponseStatus.METHOD_NOT_ALLOWED.code
    VALIDATION_ERROR = ResponseStatus.VALIDATION_ERROR.code
    
    # 业务错误
    BUSINESS_ERROR = ResponseStatus.BUSINESS_ERROR.code
    
    # 服务器错误
    INTERNAL_ERROR = ResponseStatus.INTERNAL_ERROR.code
    DATABASE_ERROR = ResponseStatus.DATABASE_ERROR.code
    REDIS_ERROR = ResponseStatus.REDIS_ERROR.code
    EXTERNAL_API_ERROR = ResponseStatus.EXTERNAL_API_ERROR.code


class ResponseMessage:
    """
    响应消息常量（向后兼容）
    """
    SUCCESS = ResponseStatus.SUCCESS.message
    BAD_REQUEST = ResponseStatus.BAD_REQUEST.message
    UNAUTHORIZED = ResponseStatus.UNAUTHORIZED.message
    FORBIDDEN = ResponseStatus.FORBIDDEN.message
    NOT_FOUND = ResponseStatus.NOT_FOUND.message
    METHOD_NOT_ALLOWED = ResponseStatus.METHOD_NOT_ALLOWED.message
    VALIDATION_ERROR = ResponseStatus.VALIDATION_ERROR.message
    BUSINESS_ERROR = ResponseStatus.BUSINESS_ERROR.message
    INTERNAL_ERROR = ResponseStatus.INTERNAL_ERROR.message
    DATABASE_ERROR = ResponseStatus.DATABASE_ERROR.message
    REDIS_ERROR = ResponseStatus.REDIS_ERROR.message
    EXTERNAL_API_ERROR = ResponseStatus.EXTERNAL_API_ERROR.message